<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :replaceFields="{ title: 'title', key: 'id' }"
          checkable
          toolbar
          title="菜单分配"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { menuApi, roleApi } from '../system-api';
  import { AddRoleInput, GrantRoleMenuInput, UpdateRoleInput } from '/@/api_base/models';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      const treeData = ref<TreeItem[]>([]);

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(treeData).length === 0) {
          treeData.value = (await menuApi.sysMenuTreeForGrantGet()).data.data as any as TreeItem[];
        }
        isUpdate.value = !!data?.isUpdate;
        let menuv = []; //{posName : [142307070910548, 142307070910547],}
        const menudata = (await roleApi.sysRoleOwnMenuGet(data.record.id)).data.data;
        for (let t of menudata) {
          menuv.push(t);
          //console.log(t.posId);
        }
        let Menuid = { menu: menuv };

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
            ...Menuid,
          });
        }
        updateSchema([
          {
            field: 'id',
            show: unref(isUpdate),
            required: unref(isUpdate),
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);

          let ret: any;
          if (!unref(isUpdate)) {
            const body: AddRoleInput = {
              roleType: 1,
              name: values.name,
              code: values.code,
              sort: values.sort,
              remark: values.remark,
            };
            ret = (await roleApi.sysRoleAddPost(body)).data;
          } else {
            const upbody: UpdateRoleInput = {
              id: values.id,
              roleType: 1,
              name: values.name,
              code: values.code,
              sort: values.sort,
              remark: values.remark,
            };
            ret = (await roleApi.sysRoleEditPost(upbody)).data;
          }
          const body: GrantRoleMenuInput = {
            id: values.id,
            grantMenuIdList: values.menu,
          };

          createMessage.info(
            '授予菜单：' + (await roleApi.sysRoleGrantMenuPost(body)).data.message
          );
          if (ret != null) {
            if (ret.code == 204) {
              closeDrawer();
              createMessage.success(ret.message);
            } else {
              createMessage.warning(ret.message + ret.message[0].messages);
            }
          } else {
            createMessage.error('未知错误');
          }
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
      };
    },
  });
</script>
